package com.example.demo.controller;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.pojo.Weather;
import com.example.demo.requestbody.user;
import com.example.demo.requestbody.weather;
import com.example.demo.responsebody.R;
import com.example.demo.service.SimpleCoderManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.SecureRandom;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.demo.common.MD5.md5;


@RestController
public class LoginController {

    @Autowired
    UserMapper usermapper;
    @Autowired
    SimpleCoderManager simpleCoderManager;

    private final StringRedisTemplate redisTemplate;
    public LoginController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/storageWeatherdata")
    public R storageWeatherdata(@RequestBody weather weatherdata) {
        try {
            Weather  sqlweatherdat = usermapper.selectWeatherdata_reporttime(weatherdata.getReporttime());
            if(sqlweatherdat != null){
                return R.ok(9003, "数据已存在",null);
            }
            else{
                int res = usermapper.insertWeatherdata(weatherdata.getCity(), weatherdata.getWeather(), weatherdata.getTemperature(), weatherdata.getHumidity(), weatherdata.getWinddirection(), weatherdata.getWindpower(), weatherdata.getReporttime());
                if(res == 1){
                    return R.ok(9001, "存储成功",null);
                }
                else{
                    return R.ok(9002, "存储失败",null);
                }
            }
        }
        catch (Exception e){
            System.out.println("存储失败" + e);
            return R.ok(9002, "存储失败",null);
        }
    }

    @PostMapping("/sendCode")
    public R sendVerificationCode(@RequestBody user request) {
        String email = request.getUsermail();
        // 验证邮箱地址
        if (email == null || email.trim().isEmpty()) {
            return R.ok(4001, "邮箱地址不能为空", null);
        }
        try {
            // 1. 生成6位随机验证码
            SecureRandom secureRandom = new SecureRandom();
            int randomNum = secureRandom.nextInt(900000) + 100000;
            String verifyCode = String.format("%06d", randomNum);
            // 2. 将验证码存入Redis，设置30秒过期
            redisTemplate.opsForValue().set(
                    buildRedisKey(email),
                    verifyCode,
                    30,
                    TimeUnit.SECONDS
            );

            // 3. 发送邮件（异步处理更佳）
            simpleCoderManager.sendemail(verifyCode,email);

            return R.ok(2003,"验证码已发送",null);
        } catch (Exception e) {
            System.out.println("验证码发送失败" + e);
            return R.ok(2004, "发送验证码失败",null);
        }
    }


//    验证验证码
    @PostMapping("/verifyCode")
    public R verifyCode(@RequestBody user request) {
        String email = request.getUsermail();
        String inputCode = request.getSmscode();

        try {
            // 1. 从Redis获取存储的验证码
            String redisKey = buildRedisKey(email);
            String storedCode = redisTemplate.opsForValue().get(redisKey);
            // 2. 校验验证码
            if (storedCode == null) {
                return R.ok(2005, "验证码已过期",null);
            }
            if (!storedCode.equals(inputCode)) {
                return R.ok(2002, "验证码错误",null);
            }
            // 3. 验证通过后删除验证码
            redisTemplate.delete(redisKey);

            return R.ok(2001,"验证通过",null);
        } catch (Exception e) {
            System.out.println("验证失败" + e);
            return R.ok(2006, "验证失败，请重试",null);
        }
    }


//    构建Redis键（格式：verify_code:邮箱）

    private String buildRedisKey(String email) {
        return "verify_code:" + email;
    }

    @PostMapping("/login")
    public R login(@RequestBody user requestuser) {
        try {
            String encoderpassword = md5(requestuser.getPassword());
            User sqluser =usermapper.loginByPhone(requestuser.getPhone(),encoderpassword);
            if(sqluser == null ){
                return R.ok(3001,"账号或密码错误",null);
            }
            else {
                return R.ok(1001,"登录成功",sqluser);
            }
        }
        catch (Exception e){
            System.out.println("登录失败" + e);
            return R.ok(1002,"登录失败,提交错误",null);
        }
    }

    @PostMapping("/loginBymail")
    public R loginBymail(@RequestBody user requestuser) {
        String email = requestuser.getUsermail();
        String inputCode = requestuser.getSmscode();
        try {
            // 1. 从Redis获取存储的验证码
            String redisKey = buildRedisKey(email);
            String storedCode = redisTemplate.opsForValue().get(redisKey);
            // 2. 校验验证码
            if (storedCode == null) {
                return R.ok(2005, "验证码已过期",null);
            }
            if (!storedCode.equals(inputCode)) {
                return R.ok(2002, "验证码错误",null);
            }
            // 3. 验证通过后删除验证码
            redisTemplate.delete(redisKey);

            return R.ok(1001,"登录成功",null);
        } catch (Exception e) {
            System.out.println("验证失败" + e);
            return R.ok(2006, "验证失败，请重试",null);
        }
    }

    @PostMapping("/loginBymailGetcode")
    public R loginBymailGetcode(@RequestBody user requestuser) {
        String email = requestuser.getUsermail();
        // 验证邮箱地址
        if (email == null || email.trim().isEmpty()) {
            return R.ok(4001, "邮箱地址不能为空", null);
        }
        try {
            int sqluser =usermapper.isRegisterByMail(email);
            if(sqluser != 0){
                try {
                    try {
                        // 1. 生成6位随机验证码
                        SecureRandom secureRandom = new SecureRandom();
                        int randomNum = secureRandom.nextInt(900000) + 100000;
                        String verifyCode = String.format("%06d", randomNum);

                        // 2. 将验证码存入Redis，设置30秒过期
                        redisTemplate.opsForValue().set(
                                buildRedisKey(email),
                                verifyCode,
                                30,
                                TimeUnit.SECONDS
                        );

                        // 3. 发送邮件（异步处理更佳）
                        simpleCoderManager.sendemail(verifyCode,email);

                        return R.ok(2003,"验证码已发送",null);
                    } catch (Exception e) {
                        System.out.println("验证码发送失败" + e);
                        return R.ok(2004, "发送验证码失败",null);
                    }
                }
                catch (Exception e){
                    System.out.println("发送验证码失败" + e);
                    return R.ok(2004,"发送验证码失败",null);
                }
            }
            else{
                return R.ok(5001,"未注册",null);
            }
        }
        catch (Exception e){
            System.out.println("登录失败" + e);
            return R.ok(1002,"登录失败",null);
        }
    }

    @PostMapping("/register")
    public R register(@RequestBody user requestuser) {
        String phone = requestuser.getPhone();
        String password = requestuser.getPassword();
        String usermail = requestuser.getUsermail();
        String username = requestuser.getUsername();
        String smscode = requestuser.getSmscode();
        String encoderpassword = md5(password);
        try {
            // 1. 从Redis获取存储的验证码
            String redisKey = buildRedisKey(usermail);
            String storedCode = redisTemplate.opsForValue().get(redisKey);
            // 2. 校验验证码
            if (storedCode == null) {
                return R.ok(2005, "验证码已过期",null);
            }
            if (!storedCode.equals(smscode)) {
                return R.ok(2002, "验证码错误",null);
            }
            // 3. 验证通过后删除验证码
            redisTemplate.delete(redisKey);

            int isResgister = usermapper.isRegister(phone);
            if(isResgister == 0){
                int ops = usermapper.insertuser(phone,username, encoderpassword, usermail);
                if(ops != 0){
                    return R.ok(5002, "注册成功", null);
                }
                else{
                    return R.ok(5003, "注册失败", null);
                }
            }
            else{
                return R.ok(5004, "该手机号已被注册", null);
            }
        }
        catch (Exception e){
            System.out.println("注册失败" + e);
            return R.ok(5003, "注册失败", null);
        }
    }

    @PostMapping("/rename")
    public R rename(@RequestBody user requestuser) {
        try {
            String encoderpassword = md5(requestuser.getPassword());
            int back = usermapper.rename(requestuser.getPhone(), requestuser.getUsername(),encoderpassword);
            if(back != 0){
                return R.ok(6001,"修改成功",null);
            }
            else{
                return R.ok(6002,"修改失败!!!",null);
            }
        }
        catch (Exception e){
            System.out.println("修改失败" + e);
            return R.ok(6002,"修改失败!!!",null);
        }
    }

    @PostMapping("/handleDeleteAccount")
    public R registerout(@RequestBody user requestuser) {
        try {
            String encoderpassword = md5(requestuser.getPassword());
            int back = usermapper.deleteuser(requestuser.getPhone(),encoderpassword);
            if(back != 0){
                return R.ok(7001,"注销成功",null);
            }
            else{
                return R.ok(7002,"注销失败",null);
            }
        }
        catch (Exception e){
            System.out.println("注销失败" + e);
            return R.ok(7002,"注销失败",null);
        }
    }

    @PostMapping("/test")
    public R test() {
        user u = new user();
        u.setUsername("test");
        u.setPassword("123");
        return R.ok(400,"登录失败",u);
    }
}
